package com.shuqi.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.AccountDataModifyController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.UserAgeModel;
import com.shuqi.model.bean.UserBookData;
import com.shuqi.model.manager.MyAccountManager;

/**
 * 我的资料界面
 * 
 * @author liyizhe
 * 
 */

public class AccountDataModifyActivity extends ActivityBase implements OnClickListener, IEventListener {

    private AccountDataModifyController controller;
    private TextView title_save = null;
    private TextView account_myid_number = null;
    private EditText name_edit = null;
    private TextView name_text = null;
    private TextView name_modify = null;
    private TextView sex_text = null;
    private TextView sex_modify = null;
    private View mPasswordView = null;
    private ImageView title_left = null;
    private BottomDialog sexDialog = null;

    /** 修改结果提示语 */
    private String result;
    private String err;// 连网错误提示
    private ToastDialog pdialog;

    /** 显示性别：0:男,1:女 */
    private final String[] GENDERS = {"男", "女"};
    /** 数据：性别：1男、2女，默认男 */
    private String gender = GENDERS[0];

    private final int INIT = EventTypeConstants.BASE;
    private final int SAVEDETAILS = INIT + 1;
    private final int INITSUCCESS = SAVEDETAILS + 1;
    private final int NETERROR = INITSUCCESS + 1;

    List<BasicNameValuePair> params;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    break;
                case SAVEDETAILS:
                    activityInitData();
                    break;
                case INITSUCCESS:
                    afterSave();
                    break;
                case NETERROR:
                    if (!TextUtils.isEmpty(err)) {
                        showMsg(err);
                        err = null;
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.controller =
                (AccountDataModifyController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_MYACCOUNTDATA, this);
        this.controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.act_account_data);
        handler.sendEmptyMessage(INIT);
        updataBookAge();
    }
    /**获取书龄并显示*/
    private void updataBookAge(){
        UserAgeModel ageModel = new UserAgeModel(this);
        IEventListener listener = new IEventListener() {
            @Override
            public void onEvent(int event, Object data) {
                if(!isFinishing()){
                    if(event == EventTypeConstants.EVENT_SUCCESS && data!=null){
                        UserBookData userBookData = (UserBookData)data;
                        if(userBookData!=null && userBookData.getBookAge()>=0){
                            showMyBookAge(userBookData.getBookAge()+"天");
                        }else{
                            showMyBookAge("获取失败");
                        }
                    }else{
                        showMyBookAge("获取失败");
                    }
                }
            }
        };
        ageModel.addEventListener(listener );
        ageModel.loadData();
        showMyBookAge("获取中...");
    }
    
    /**显示书龄*/
    private void showMyBookAge(final String bookAge){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ((TextView)findViewById(R.id.account_mybookage_number)).setText(bookAge);
            }
        });
    }

    @Override
    public void onEvent(int event, Object data) {

        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                // 读取数据 写处理逻辑
                result = (String) data;
                handler.sendEmptyMessage(INITSUCCESS);
                break;
            case EventTypeConstants.EVENT_EXC_TIMEOUT:
                err = getString(R.string.msg_exception_timeout);
                handler.sendEmptyMessage(NETERROR);
                break;
            case EventTypeConstants.EVENT_EXC_PARSER:
                err = getString(R.string.msg_exception_parser);
                handler.sendEmptyMessage(NETERROR);
                break;
            default:
                err = getString(R.string.net_error_text);
                handler.sendEmptyMessage(NETERROR);
                break;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (pdialog != null && pdialog.isShowing()) {
                    pdialog.dismiss();
                }
            }
        });
    }

    private boolean isVipUserByEmailOrMobile() {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        return MyAccountManager.isVipUserByEmailOrMobile(user);
    }

    /**
     * 初始化控件
     */
    @Override
    public void activityLogicForward() {
        title_save = (TextView) findViewById(R.id.title_save);
        title_left = (ImageView) findViewById(R.id.title_left);
        account_myid_number = (TextView) findViewById(R.id.account_myid_number);
        name_edit = (EditText) findViewById(R.id.name_edit);
        name_text = (TextView) findViewById(R.id.name_text);
        name_modify = (TextView) findViewById(R.id.name_modify);
        sex_text = (TextView) findViewById(R.id.sex_text);
        sex_modify = (TextView) findViewById(R.id.sex_modify);
        mPasswordView = findViewById(R.id.password);
        UserInfo userInfo = MyAccountManager.getInstance(AccountDataModifyActivity.this);
        String userId = userInfo.getUserId();
        String userName = userInfo.getNickName();
        gender = userInfo.getGender();
        account_myid_number.setText(userId);
        name_text.setText(userName);
        if (gender != null && gender.equals("2")) {
            sex_text.setText("女");
        } else {
            sex_text.setText("男");
        }

        title_save.setOnClickListener(this);
        title_left.setOnClickListener(this);
        name_modify.setOnClickListener(this);
        sex_modify.setOnClickListener(this);
        this.findViewById(R.id.password).setOnClickListener(this);

        if (isVipUserByEmailOrMobile()) {
            mPasswordView.setVisibility(View.VISIBLE);
            findViewById(R.id.password_line).setVisibility(View.VISIBLE);
        } else {
            mPasswordView.setVisibility(View.GONE);
            findViewById(R.id.password_line).setVisibility(View.GONE);
        }
    }

    @Override
    public void activityInitData() {
        if (pdialog == null) {
            pdialog = new ToastDialog(this);
        }
        pdialog.loading("正在修改...");
        params = setParams();
        controller.handle(0, params);
    }

    private CheckBox maleBox;
    private CheckBox famaleBox;
    private TextView tvOK;

    public void showBottomDialog() {
        if (sexDialog == null) {
            View view = View.inflate(this, R.layout.view_sex_bottom_dialog, null);
            sexDialog = new BottomDialog(this, view);
            maleBox = (CheckBox)sexDialog.findViewById(R.id.view_dialog_male);
            famaleBox = (CheckBox) sexDialog.findViewById(R.id.view_dialog_famale);
            tvOK = (TextView) sexDialog.findViewById(R.id.view_dialog_ok);
            maleBox.setOnClickListener(this);
            famaleBox.setOnClickListener(this);
            tvOK.setOnClickListener(this);
        }

        if (sex_text.getText().toString().equals("男")) {
            maleBox.setChecked(true);
            famaleBox.setChecked(false);
        } else if (sex_text.getText().toString().equals("女")) {
            famaleBox.setChecked(true);
            maleBox.setChecked(false);
        }
        sexDialog.show();
    }

    /**
     * 提交修改资料的连网结束后的操作
     */
    public void afterSave() {
        if (!TextUtils.isEmpty(result)) {
            showMsg(result);
            if (result.contains("成功")) {
                UserInfo userInfo = MyAccountManager.getInstance(AccountDataModifyActivity.this);

                String nickname = name_text.getText().toString();
                if (name_edit.getVisibility() == View.VISIBLE) {
                    nickname = name_edit.getText().toString();
                }
                userInfo.setNickName(nickname);
                userInfo.setGender(gender);
                setResult(Activity.RESULT_OK);
                AccountActivity.callRefreshAccountOnResume();
                ActivityManager.getInstance().finishActivity(this);
            }
            result = null;
        } else {
            showMsg(err);
        }
    }

    /**
     * @Des 描述 获取接口组织参数
     * @author Tim
     * @return List<BasicNameValuePair>
     */
    public List<BasicNameValuePair> setParams() {
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        String key = "c56cf32e9a52a265ae47cd50570266cc";
        long timestamp = System.currentTimeMillis();
        String strTimestamp = timestamp + "";
        String md5_key_sb = key + timestamp;
        String md5_key = Util.MD5(md5_key_sb.toString());
        params.add(new BasicNameValuePair("key", md5_key));// md5
        params.add(new BasicNameValuePair("timestamp", strTimestamp));// 时间戳
        params.add(new BasicNameValuePair("userid", MyAccountManager.getInstance(
                AccountDataModifyActivity.this).getUserId()));// 用户id

        // 判断是否点击屏幕其他地方使edit不可见
        String nickname = name_text.getText().toString();
        if (name_edit.getVisibility() == View.VISIBLE) {
            nickname = name_edit.getText().toString();
        }
        params.add(new BasicNameValuePair("nickname", nickname));// 昵称

        if (sex_text.getText().equals(GENDERS[0])) {
            params.add(new BasicNameValuePair("gender", "1"));// 性别
            gender = "1";
        } else {
            params.add(new BasicNameValuePair("gender", "2"));
            gender = "2";
        }
        return params;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.title_save: {
                // UserInfo userInfo = MyAccountManager.getInstance(MyAccountDataActivity.this);
                String userName = name_text.getText().toString().trim();
                if (userName.length() <= 0) {
                    showMsg("昵称没填呀");
                    return;
                }
                // if (userName.equals(userInfo.getNickName()) && (gender == userInfo.getGender()))
                // {
                // showMsg("资料未修改");
                // return;
                // }
                handler.sendEmptyMessage(SAVEDETAILS);
                break;
            }
            case R.id.name_modify: {
                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                name_edit.setText(name_text.getText().toString());
                name_text.setVisibility(View.GONE);
                name_modify.setVisibility(View.GONE);
                name_edit.setVisibility(View.VISIBLE);
                name_edit.setFocusable(true);
                name_edit.setFocusableInTouchMode(true);
                name_edit.requestFocus();
                name_edit.setSelection(name_text.getText().toString().length());

                imm.showSoftInput(name_edit, 0);
                break;
            }
            case R.id.sex_modify:
                if (name_edit.getVisibility() != View.GONE) {
                    changeNameEditMode(false);
                }
                showBottomDialog();
                break;
            case R.id.password: {
                Intent intent =
                        new Intent(AccountDataModifyActivity.this, PasswordModifyActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, this);
                break;
            }
            case R.id.view_dialog_male: {
                maleBox.setChecked(true);
                famaleBox.setChecked(false);
                break;
            }
            case R.id.view_dialog_famale: {
                maleBox.setChecked(false);
                famaleBox.setChecked(true);
                break;
            }
            case R.id.view_dialog_ok: {
                if (maleBox.isChecked()) {
                    sex_text.setText(GENDERS[0]);
                    gender = "1";
                } else {
                    sex_text.setText(GENDERS[1]);
                    gender = "2";
                }
                sexDialog.dismiss();
                break;
            }
        }
    }

    /**
     * 屏幕触摸事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (name_edit == null || name_modify == null || name_text == null) {
            return super.onTouchEvent(event);
        }
        InputMethodManager imm =
                (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(name_edit.getWindowToken(), 0);
        if (name_edit.getVisibility() == View.GONE) {// 一定要先判断一下，不然只要你一点屏幕就会清空你标题上的文字
            return false;
        } else {
            name_text.setVisibility(View.VISIBLE);
            name_modify.setVisibility(View.VISIBLE);
            name_edit.setVisibility(View.GONE);
            name_text.setText(name_edit.getText().toString());
        }
        return super.onTouchEvent(event);
    }

    private void changeNameEditMode(boolean isEdit) {
        if (isEdit) {
            name_edit.setText(name_text.getText().toString());
            name_text.setVisibility(View.GONE);
            name_modify.setVisibility(View.GONE);
            name_edit.setVisibility(View.VISIBLE);
            name_edit.setFocusable(true);
        } else {
            name_text.setVisibility(View.VISIBLE);
            name_modify.setVisibility(View.VISIBLE);
            name_edit.setVisibility(View.GONE);
            name_text.setText(name_edit.getText().toString());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
